package de.core.gameplay.actor.misc;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;

import javax.swing.JLabel;

import de.core.gameplay.actor.AbstractActor;


public class Label extends AbstractActor {

    private String text;
    private Font font;
    private Color color;


    public Label(String aText, Font aFont, int aX, int aY) {
        this(aText, aFont, new Color(255, 255, 255), aX, aY);
    }

    public Label(String aText, Font aFont, Color aColor, int aX, int aY) {
        super(createImage(aText, aFont, aColor), aX, aY);
        text = aText;
        font = aFont;
        color = aColor;
    }

    public void setText(String aText) {
        text = aText;
        updateImage();
    }

    public void setFont(Font aFont) {
        font = aFont;
        updateImage();
    }

    public void setColor(Color aColor) {
        color = aColor;
        updateImage();
    }

    private void updateImage() {
        setImage(createImage(text, font, color));
    }

    private static BufferedImage createImage(String aText, Font aFont, Color aColor) {
        FontMetrics fontMetrics = getFontMetricsForFont(aFont);
        int textWidth = fontMetrics.stringWidth(aText);
        int textHeight = fontMetrics.getHeight();

        if (textWidth == 0) {
            textWidth = 1;
        }
        BufferedImage image = new BufferedImage(textWidth, textHeight, BufferedImage.TYPE_INT_ARGB);

        Graphics drawGraphics = image.getGraphics();
        drawGraphics.setFont(aFont);
        drawGraphics.setColor(aColor);
        drawGraphics.drawString(aText, 0, textHeight);
        drawGraphics.dispose();

        return image;
    }

    private static FontMetrics getFontMetricsForFont(Font aFont) {
        JLabel label = new JLabel();
        return label.getFontMetrics(aFont);
    }

    @Override
    protected void act() {
        // The default implementation does not do anything...
    }

    @Override
    protected final Point2D getImageRenderLocation(float aInterpolation) {
        return getLocation();
    }
}
